var express = require('express');
const req = require('express/lib/request');
const res = require('express/lib/response');
const { insert } = require('../dao/infosDao');
var router = express.Router();
const infosService = require('../service/infosService');


//查询
router.get('/', async function (req, res) {
    let { type, value, startDate, endDate, current, pageSize} = req.query;
    // console.log(req.query);
    let searchObj = {};
    // console.log(type,value);
    if (startDate) {
        searchObj["createTime"] = { $gte: startDate }
    }
     if (endDate) {
        searchObj["createTime"] = { ...searchObj["createTime"], $lte: endDate }
    }
    if (type) {
        if (type=="watches") {
            searchObj[type]=value;  //浏览人数精确查找
        }else{
            searchObj[type]={$regex:value}  //标题是模糊查找
        }
    }
    let data = await infosService.find(searchObj,
        { current: current || 1, pageSize: pageSize || 5 }) //如果没分页的情况，不然要报错
    // console.log(data);
    res.send({ data })
})

//增加
router.post('/', async function (req, res) {
    let { title, createTime, watches, content} = req.body;
    console.log(req.body);
    let data = await infosService.insert({ title, createTime, watches, content });
    res.send({ data })
})

//删除
router.delete('/:id', async function (req, res) {   //：id动态路径（参数会发生变化），路径后面的参数才用params
    let { id } = req.params;
    let data = await infosService.remove(id)
    console.log(data);
    res.send({ data })
})

////修改
//先通过Id查找对象
router.get('/:id', async function (req, res) {
    let { id } = req.params;  //get提交query
    let data = await infosService.findById(id);
    res.send({ data })
})
//put根据id修改
router.put('/:id', async function (req, res) { 
    // console.time('test')  //检测代码执行时间
    let { id } = req.params  
    let { title, createTime, watches, content} = req.body;  //post提交是body
    let data = await infosService.update(id, { title, createTime, watches, content})  //传参时就分开写了
    console.log(data);
    res.send({ data })
    // console.timeEnd('test')
  
})
module.exports = router;

